package com.gm.servlet;

import com.gm.bean.CheckUpdateResult;
import com.google.gson.Gson;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by Mouse on 2017/6/14.
 */
public class H5100UpdateServlet extends HttpServlet {

    private File h5100UpdateDir;
    private File bsToolDir;
    private File h5100ApkDir;
    private File h5100PatchDir;
    private File tempDir;

    private File bsdiff;

    @Override
    public void init(ServletConfig config) throws ServletException {

        String h5100UpdateDirPath = config.getInitParameter("h5100_update_dir");
        if (!h5100UpdateDirPath.endsWith(File.separator))
            h5100UpdateDirPath = h5100UpdateDirPath + File.separator;
        String bsToolDirPath = h5100UpdateDirPath + "tools" + File.separator + "bs";
        String h5100ApkDirPath = h5100UpdateDirPath + "files" + File.separator + "h5100Apk";
        String h5100PatchDirPath = h5100UpdateDirPath + "files" + File.separator + "h5100Patch";
        String tempDirPath = h5100UpdateDirPath + "temp";

        System.out.println(h5100UpdateDirPath);
        System.out.println(bsToolDirPath);
        System.out.println(h5100ApkDirPath);
        System.out.println(h5100PatchDirPath);
        System.out.println(tempDirPath);

        h5100UpdateDir = new File(h5100UpdateDirPath);
        h5100UpdateDir.mkdirs();

        bsToolDir = new File(bsToolDirPath);
        bsToolDir.mkdirs();

        h5100ApkDir = new File(h5100ApkDirPath);
        h5100ApkDir.mkdirs();

        h5100PatchDir = new File(h5100PatchDirPath);
        h5100PatchDir.mkdirs();

        tempDir = new File(tempDirPath);
        tempDir.mkdirs();

        bsdiff = new File(bsToolDirPath, "bsdiff.exe");

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");

        String action = request.getParameter("action");
        if (action.equals("checkUpdate")) {
            checkUpdate(request, response);
        } else if (action.equals("downloadPatch")) {
            downloadPatch(request, response);
        }

    }

    private void checkUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("----checkUpdate start----");

        String currentVersionCode = request.getParameter("currentVersionCode");
        System.out.println("currentVersionCode:" + currentVersionCode);

        int latest = 1;
        File[] dirs = h5100ApkDir.listFiles();
        for (File dir : dirs) {
            if (dir.isDirectory()) {
                try {
                    int i = Integer.parseInt(dir.getName());
                    latest = Math.max(latest, i);
                } catch (Exception e) {
                    continue;
                }
            }
        }


        //响应

        File file = new File(
                h5100ApkDir + File.separator + String.valueOf(latest),
                "README.md"
        );
        if (file.exists() && file.isFile()) {

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            CheckUpdateResult checkUpdateResult = new CheckUpdateResult();
            checkUpdateResult.setLatestVersionCode(latest);
            checkUpdateResult.setLatestVersionName(br.readLine());
            StringBuffer sb = new StringBuffer();
            String str = null;
            while ((str = br.readLine()) != null)
                sb.append(str + "\n");
            checkUpdateResult.setNote(sb.toString());

            fr.close();
            br.close();

            String jsonString = new Gson().toJson(checkUpdateResult, CheckUpdateResult.class);
            System.out.println("resp:\n" + jsonString);
            response.getWriter().write(jsonString);
        }

        System.out.println("----checkUpdate end----");
    }


    private void downloadPatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("----downloadPatch start----");

        String currentVersionCode = request.getParameter("currentVersionCode");
        String latestVersionCode = request.getParameter("latestVersionCode");
        System.out.println("currentVersionCode:" + currentVersionCode);
        System.out.println("latestVersionCode:" + latestVersionCode);


        //初始化资源
        File oldApk = new File(
                h5100ApkDir + File.separator + currentVersionCode,
                "h5100-release.apk");
        if (!oldApk.exists() || !oldApk.isFile()) {
            return;
        }

        File newApk = new File(
                h5100ApkDir + File.separator + latestVersionCode,
                "h5100-release.apk");
        if (!newApk.exists() || !newApk.isFile()) {
            return;
        }

        File patch = new File(
                h5100PatchDir + File.separator + currentVersionCode + "_" + latestVersionCode,
                "patch");
        if (!patch.exists()) {
            new File(patch.getParent()).mkdirs();

            patch.createNewFile();
            System.out.println("bsdiff...");
            //生成差量包
            String command = bsdiff.getAbsolutePath() +
                    " " + oldApk +
                    " " + newApk +
                    " " + patch;
            System.out.println(command);
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(command);
                process.waitFor();
            } catch (Exception e) {
            } finally {
                if (process != null) {
                    process.destroy();
                    process = null;
                }
            }
        }

        //响应
        System.out.println("resp:\n" + URLEncoder.encode(patch.getName(), "utf-8"));
        response.setContentType("application/octet-stream");
        response.setContentLengthLong(patch.length());
        response.setHeader(
                "content-disposition",
                "attachment; filename=" + URLEncoder.encode(patch.getName(), "utf-8")
        );

        FileInputStream fis = new FileInputStream(patch);
        try {
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                response.getOutputStream().write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                fis.close();
            }
        }

        System.out.println("----downloadPatch end----");
    }


}
